/**
 * 修改登陆密码
 * /general/setpassword
 */

const User_info = require('../../models/usersInfo')
const Users = require('../../models/users')
const utils = require('../../utils/index')
const $ = require('../../utils/common')
const MySQLManager = require('../../utils/MySQLManager');
const sequelize = MySQLManager

const set_password = async function(req, res) {
    try {
        if (!req.body.user_password){
            $.sendMessage(res, 1015, '参数user_password为有效代码')
            return
        }
        
        if (req.body.user_password.length < 6 || req.body.user_password.length > 12) {
            $.sendMessage(res, 1015, '参数user_password长度为6 - 12 个字符')
            return
        }

         // 事务
        return sequelize.transaction(function (t) {

            return Users.update(
            {
                user_password : req.body.user_password + ''
            },
            {
                where: {
                    user_name: req.user_name + ''
                }
            }
            , 
            {transaction: t}).then(function (user) {
            return User_info.update(
                {
                    user_password : req.body.user_password + ''
                },
                {
                    where: {
                        user_name: req.user_name + ''
                    }
                }
                , {transaction: t})
            })
        
        })
        // 请求完整完成
        .then(function (result) {
            res.json({
                code: 200,
                message: '修改密码成功',
                result: result
            })
         
            utils.create_a_log(req, '学生信息', '密码修改')
            return

        })
        // 处理sequalize异常
        .catch(function (err) {
            res.json({
                code: 1017,
                message: '修改密码失败',
                err: 'err' + err
            })
            
        })
    }

    catch(err) {
        $.sendMessage(res, 0000, "err:" + err)
        return
    }
}

module.exports = set_password